﻿using _537AppStore_API.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace _537_App_Store.Form
{
    /// <summary>
    /// UploadWindow.xaml 的交互逻辑
    /// </summary>
    public partial class UploadWindow : Window
    {
        public UploadWindow()
        {
            InitializeComponent();
        }

        private void CancelButon_Click(object sender, RoutedEventArgs e)
        {
            //var text=GetInstallerType(Application_InstallerType.SelectedItem.ToString());
            //MessageBox.Show(text.ToString());
            //Close();
        }

        private async void Application_Upload_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Application_Author.Text))
            {
                MessageBox.Show("请填写作者名称");
                return;
            }
            if (string.IsNullOrEmpty(Application_Name.Text))
            {
                MessageBox.Show("请填写应用名称");
                return;
            }
            if (string.IsNullOrEmpty(Application_IconURL.Text))
            {
                MessageBox.Show("请填写图标路径");
                return;
            }
            if (string.IsNullOrEmpty(Application_DownloadURL.Text))
            {
                MessageBox.Show("请填写下载路径");
                return;
            }
            if (string.IsNullOrEmpty(Application_InstallCommand.Text))
            {
                MessageBox.Show("请填写安装命令");
                return;
            }
            if (string.IsNullOrEmpty(Application_RunFile.Text))
            {
                MessageBox.Show("请填写运行文件");
                return;
            }
            if (string.IsNullOrEmpty(Application_MD5.Text))
            {
                MessageBox.Show("请填写MD5");
                return;
            }
            var select = Application_InstallerType.SelectedItem.ToString();
            var installerType = new _537AppStore_API.Model.InstallerType();
            switch (select)
            {
                case "exe":
                    installerType = _537AppStore_API.Model.InstallerType.exe;
                    break;
                case "msi":
                    installerType = _537AppStore_API.Model.InstallerType.msi;
                    break;
                case "zip":
                    installerType = _537AppStore_API.Model.InstallerType.zip;
                    break;
                case "appx":
                    installerType = _537AppStore_API.Model.InstallerType.appx;
                    break;
            }
            var app = new _537AppStore_API.Model.Application()
            {
                Author = Application_Author.Text,
                Name = Application_Name.Text,
                Icon = Application_IconURL.Text,
                DownloadUrl = Application_DownloadURL.Text,
                Category = Application_Category.Text,
                Description = Application_Description.Text,
                id = Guid.NewGuid(),
                InstallCommand = Application_InstallCommand.Text,
                LastUpdated = DateTime.Now,
                License = Application_License.Text,
                MD5 = Application_MD5.Text,
                RunFile = Application_RunFile.Text,
                Website = Application_Website.Text,
                Version = Application_Version.Text,
                InstallerType = installerType
            };
            //API POST 上传，app为参数
            //API服务器地址https://537store.irabbitstudio.com.cn/api/Application
            // 创建HttpClient（实际项目中建议复用HttpClient实例）
            using (var httpClient = new HttpClient())
            {
                try
                {
                    // 序列化对象为JSON
                    var json = JsonSerializer.Serialize(app);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 发送POST请求
                    var response = await httpClient.PostAsync($"{MainWindow.ServerAddress}/api/Application", content);

                    // 确保响应成功
                    response.EnsureSuccessStatusCode();

                    // 读取响应内容（可选，根据API返回格式调整）
                    var responseBody = await response.Content.ReadAsStringAsync();
                    MessageBox.Show($"上传成功！响应: {responseBody}");
                    Close();
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                    Close();
                }
                catch (JsonException ex)
                {
                    MessageBox.Show($"JSON序列化失败: {ex.Message}");
                    Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                    Close();
                }

            }

        }

        private async void Comma_UploadButon_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Command_Name.Text))
            {
                MessageBox.Show("请填写命令名称");
                return;
            }
            if (string.IsNullOrEmpty(Command_Value.Text))
            {
                MessageBox.Show("请填写命令的值");
                return;
            }
            if (string.IsNullOrEmpty(Command_Description.Text))
            {
                MessageBox.Show("请填写命令描述");
                return;
            }
            var command = new _537AppStore_API.Model.Command()
            {
                CommandName = Command_Name.Text,
                CommandValue = Command_Value.Text,
                CommandDescription = Command_Description.Text,
                id = Guid.NewGuid(),
                Author = System.Environment.UserName,
                CreateTime = DateTime.Now
            };
            using (var httpClient = new HttpClient())
            {
                try
                {
                    var json = JsonSerializer.Serialize(command);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    var response = await httpClient.PostAsync($"{MainWindow.ServerAddress}/api/Command", content);
                    // 确保响应成功
                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    MessageBox.Show($"上传成功！响应: {responseBody}");
                    Close();
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                    Close();
                }
                catch (JsonException ex)
                {
                    MessageBox.Show($"JSON序列化失败: {ex.Message}");
                    Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                    Close();
                }
            }
        }

        private async void WebSite_UploadButon_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(WebSite_Name.Text))
            {
                MessageBox.Show("请填写网站名称");
                return;
            }
            if (string.IsNullOrEmpty(WebSite_IconURL.Text))
            {
                MessageBox.Show("请填写网站图标");
                return;
            }
            if (string.IsNullOrEmpty(WebSite_URL.Text))
            {
                MessageBox.Show("请填写网站地址");
                return;
            }
            if (string.IsNullOrEmpty(WebSite_Category.Text))
            {
                MessageBox.Show("请填写网站分类");
                return;
            }
            if (string.IsNullOrEmpty(WebSite_Description.Text))
            {
                MessageBox.Show("请填写网站描述");
                return;
            }
            var website = new _537AppStore_API.Model.Website()
            {
                Name = WebSite_Name.Text,
                Icon = WebSite_IconURL.Text,
                Url = WebSite_URL.Text,
                Category = WebSite_Category.Text,
                Description = WebSite_Description.Text,
                Author = System.Environment.UserName,
                CreateTime = DateTime.Now,
                id = Guid.NewGuid()
            };
            using (var httpClient = new HttpClient())
            {
                try
                {
                    var json = JsonSerializer.Serialize(website);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    var response = await httpClient.PostAsync($"{MainWindow.ServerAddress}/api/Website", content);
                    // 确保响应成功
                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    // MessageBox.Show($"上传成功！响应: {responseBody}");
                    Close();
                }
                catch (HttpRequestException ex)
                {
                    MessageBox.Show($"请求失败: {ex.Message}");
                }
            }
        }
    }
}
